<template>
    <div class="Main">
        <app-header :active="activeType"></app-header>
        <div class="page_content">
            <div class="page_content_top">
                <x-card class="card">
                    <div class="page_content__left">
                        <div class="page_content__left__video_audio">
                            <div class="video-container" v-if="detailInfo.type == 'video' && detailInfo.localUrl" >
                                <video id="video" ref="video" controls width="100%" height="400px">
                                    <source src="" type="application/x-mpegURL">
                                </video>
                            </div>
                            <audio v-if="detailInfo.type == 'audio' && detailInfo.localUrl" ref="audio" :src="detailInfo.localUrl.replace('http://124.16.154.205:9000/','/minioUrl/')" controls></audio>
                        </div>
                        <div class="page_content__left_intro">
                            <div class="title">
                                摘要
                            </div>
                            <base-divider></base-divider>
                            <div class="intro">
                                {{ detailInfo.intro }}
                            </div>
                        </div>
                    </div>
                </x-card>
                <div class="page_content__right">
                    <x-card class="card">
                        <div class="page_content__right—top">
                            <div class="page_content__right__title"> {{ detailInfo.name }}</div>
                            <div class="page_content__right__info top_20"> 主讲人：{{ detailInfo.speaker }}</div>
                            <div class="page_content__right__info top_20"> 主办单位：{{ detailInfo.organizer }}</div>
                            <div class="page_content__right__info top_20"> 发行单位：{{ detailInfo.issuingUnitName }}</div>
                            <base-divider></base-divider>
                            <div class="page_content__right__info" v-if="detailInfo.category"> 分类：{{ detailInfo.category }}</div>
                            <div class="page_content__right_tag">
                                <base-tag type="primary" v-for="tag,index in detailInfo.tagList" :key="'tag'+index"> {{tag}} </base-tag>
                                <base-tag type="warning" v-for="category,index in detailInfo.categoryList" :key="'category'+index">{{category}} </base-tag>
                            </div>
                        </div>
                    </x-card>
                    <x-card class="card">
                        <div class="page_content__right—bottom">
                            <div class="page_content__right—bottom_price_order">
                                <div class="page_content__right—bottom_price">
                                    ￥{{ detailInfo.price }}
                                </div>
                                <base-button type="primary" @click="addOrder(detailInfo)"> 立即购买  </base-button>
                                <base-button type="text" @click="addCart(detailInfo)"> 加入购物车  </base-button>
                            </div>
                            <div class="page_content__right__operate">
                                <div class="simple-action"> <svg viewBox="0 0 1024 1024" width="22" height="22" fill="currentColor" class="Icon"><path d="M563.2 607.168a52.224 52.224 0 0 1 0-0.192v-0.064-0.192a460.48 460.48 0 0 1 223.104-394.56 51.2 51.2 0 0 1 52.928 87.68A359.04 359.04 0 0 0 699.648 454.4 153.472 153.472 0 1 1 563.2 607.168z m-409.6 0a52.224 52.224 0 0 1 0-0.192v-0.064-0.192a460.48 460.48 0 0 1 223.104-394.56 51.2 51.2 0 0 1 52.928 87.68A359.04 359.04 0 0 0 290.048 454.4 153.472 153.472 0 1 1 153.6 607.168z"></path></svg>引用 </div>
                                <div :class="{'simple-action collect':true, 'is-active':detailInfo.userCollectionStatus == 1}" @click="operateCollect(detailInfo)">
                                 <svg fill="currentColor" viewBox="0 0 24 24" width="18" height="18" class="Icon Icon--Collect"><path d="M5.515 19.64l.918-5.355-3.89-3.792c-.926-.902-.639-1.784.64-1.97L8.56 7.74l2.404-4.871c.572-1.16 1.5-1.16 2.072 0L15.44 7.74l5.377.782c1.28.186 1.566 1.068.64 1.97l-3.89 3.793.918 5.354c.219 1.274-.532 1.82-1.676 1.218L12 18.33l-4.808 2.528c-1.145.602-1.896.056-1.677-1.218z" fill-rule="evenodd"></path></svg>
                                 {{detailInfo.userCollectionStatus == 1?'取消收藏':'收藏'}}
                                 </div>
                                <div class="simple-action recommend" :class="{'is-active':detailInfo.userRecommendationStatus == 1}" @click="opreateRecommend(detailInfo)"> <svg data-v-2c035fc6="" width="1.2em" height="1.2em" viewBox="0 0 24 24" fill="currentColor" class="Icon Icon--like"><path data-v-2c035fc6="" d="M12.004 4.934c1.015-.944 2.484-1.618 3.98-1.618 3.48 0 6.53 3.265 6.15 7.614-.11 1.254-.686 2.55-1.458 3.753-.778 1.215-1.79 2.392-2.845 3.419-1.054 1.028-2.168 1.923-3.161 2.566a9.96 9.96 0 01-1.41.777c-.418.182-.862.32-1.268.32s-.848-.137-1.267-.317a9.918 9.918 0 01-1.407-.771c-.992-.64-2.103-1.53-3.156-2.555-1.052-1.024-2.062-2.2-2.84-3.417-.77-1.208-1.346-2.51-1.456-3.775-.38-4.349 2.67-7.614 6.15-7.614 1.484 0 2.983.673 3.988 1.618z" fill-rule="evenodd" clip-rule="evenodd"></path></svg> 
                                {{detailInfo.userRecommendationStatus == 1?'取消推荐':'推荐'}} {{ detailInfo.countRecommendation }} </div>
                            </div>
                        </div>
                    </x-card>
                </div>
            </div>

            <x-card class="card">
                <div class="page_content__bottom">
                    <div class="page_content__bottom__title">
                        相关推荐
                    </div>
                    <base-divider></base-divider>
                    <base-tabs v-model="activeName" @tab-click="handleClick">
                        <base-tab-pane name="related" :label=relatedLabel>
                            <div v-if="total!=0" class="page_content__bottom__content">
                                <div class="page_content__bottom__content__item">
                                    <template v-for="(item,index) in dataList">
                                        <VideoAudioList :ref="'videoAudioList'+index+type" :key="index+type+item.id" :currItem="item" :type="type"></VideoAudioList>
                                    </template>
                                </div>
                            </div>
                            <Empty v-else :height="'300px'"></Empty>
                        </base-tab-pane>
                        <base-tab-pane name="speaker" label="同主讲人">
                            <div v-if="total!=0" class="page_content__bottom__content">
                                <div class="page_content__bottom__content__item">
                                    <template v-for="(item,index) in dataList">
                                        <VideoAudioList :ref="'videoAudioList'+index+type" :key="index+type+item.id" :currItem="item" :type="type"></VideoAudioList>
                                    </template>
                                </div>
                            </div>
                            <Empty  v-else  :height="'300px'"></Empty>
                        </base-tab-pane>
                        <base-tab-pane name="category" label="同分类">
                            <div v-if="total!=0" class="page_content__bottom__content">
                                <div class="page_content__bottom__content__item">
                                    <template v-for="(item,index) in dataList">
                                        <VideoAudioList :ref="'videoAudioList'+index+type" :key="index+type+item.id" :currItem="item" :type="type"></VideoAudioList>
                                    </template>
                                </div>
                            </div>
                            <Empty v-else :height="'300px'"></Empty>
                        </base-tab-pane>
                    </base-tabs>
                            
                </div>
            </x-card>

        </div>
        <app-footer></app-footer>
    </div>
</template>
<script>
import {XCard} from "@zkwq/business";
import {GetVideoAudio,ListVideoAudio} from '../service/videoAudio'
import {EditCart} from '../service/cart'
import {EditOrder} from '../service/order'
import AppHeader from './components/AppHeader.vue';
import AppFooter from './components/AppFooter.vue';
import VideoAudioList from './components/VideoAudioList.vue';
import Empty from './components/Empty.vue';
import Hls from 'hls.js'
import {AddRecommendation, CancelRecommendation} from '../service/recommendation'
import {AddCollection, CancelCollection} from '../service/collection'
export default {
    name: 'VideoAudioDetail',
    components: {
        AppHeader,
        AppFooter,
        VideoAudioList,
        Empty,
        XCard
    },
    data() {
        return {
            detailInfo: {},
            id:"",
            activeName:"related",
            dataList:[],
            total:0,
        }
    },
    computed: {
        activeType() {
            return 'digitalResource-'+this.detailInfo.type;
        },
        relatedLabel() {
          if (this.detailInfo.type === 'video') {
            return '相关视频';
          } else if (this.detailInfo.type === 'audio') {
            return '相关音频';
          } else if (this.detailInfo.type === 'text') {
            return '相关文字';
          }
        }
    },
    mounted() {
        this.id = this.$route.params.id;
        this.getDetailInfo()
    },
    methods: {
        getDetailInfo() {
            GetVideoAudio(this.id).then(res => {
                this.detailInfo = res.data;
                this.detailInfo.tagList = this.detailInfo.tag?.split(";").filter(f => f) || [];
                this.detailInfo.categoryList = this.detailInfo.category?.split(";").filter(f => f) || [];
                let sysMagazine = this.detailInfo.sysMagazine
                if (sysMagazine) {
                    if (sysMagazine.magazineType == 2 && sysMagazine.children) {
                        this.detailInfo.issuingUnitName = sysMagazine.children.map(c => c.name).join(';')
                    } else {
                        this.detailInfo.issuingUnitName = sysMagazine.magazineName
                    }
                }

                if (!this.detailInfo.localUrl && this.detailInfo.url){
                    this.detailInfo.localUrl = this.detailInfo.url
                }
                if (this.detailInfo.type == 'video' && this.detailInfo.localUrl){
                    this.$nextTick(() => {
                        const video = this.$refs.video;
                        let videoUrl = this.detailInfo.localUrl.replace('http://124.16.154.205:9000/','/minioUrl/')
                        if (Hls.isSupported()) {
                            const hls = new Hls()
                            hls.loadSource(videoUrl)
                            hls.attachMedia(video)
                            hls.on(Hls.Events.ERROR, (event, data) => {
                                console.error("hls.js 播放错误：", data);
                            });
                            hls.on(Hls.Events.MANIFEST_PARSED, (event, data) => {
                                console.log("hls.js 播放成功：", data);
                            });
                        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
                            video.src = videoUrl
                        } else {
                            console.error("不支持HLS播放");
                        }

                        //试看 3 分钟逻辑
                        if (true) {
                            let hasShownWarning = false;
                            video.addEventListener("timeupdate", () => {
                                if (video.currentTime >= 180 && !hasShownWarning) { // 超过3分钟
                                    video.pause();
                                    video.currentTime = 180; // 锁定在3分钟
                                    this.$message.warning("试看已结束，请购买后继续观看");
                                    hasShownWarning = true
                                    video.src = ''; // 清空视频源
                                    video.disabled = true; // 禁用视频播放器
                                    video.style.pointerEvents = 'none'; // 禁用点击交互
                                }
                            });
                        }
                    })
                }
                this.getRecommandList()
            })
        },
        handleClick(tab, event) {
            this.activeName = tab.name;
            this.getRecommandList()
        },
        getRecommandList(){
            let params = {
                page:1,
                pageSize:5,
                status:"1",
                type:this.detailInfo.type,
                excludeId:this.detailInfo.id,
                isBrowser:true,
            }
            if (this.activeName == 'speaker'){
                params.speaker = this.detailInfo.speaker;
            }
            if (this.activeName == 'category'){
                params.category = this.detailInfo.categoryList;
                if (!params.category || params.category.length == 0) {
                    this.total = 0
                    this.dataList = []
                    return
                }
            }
            if (this.activeName == 'related'){
                params.tag = this.detailInfo.tagList;
                if (!params.tag || params.tag.length == 0) {
                    this.total = 0
                    this.dataList = []
                    return
                }
            }
            ListVideoAudio(params).then(res=>{
                let data = res.data;
                this.total = data.total;
                this.dataList = data?.records?.map(e => {
                    e.tagList = e.tag?.split(";").filter(f => f) || [];
                    e.categoryList = e.category?.split(";").filter(f => f) || [];
                    let sysMagazine = e.sysMagazine;
                    if(sysMagazine){
                        if (sysMagazine.magazineType==1) {
                            e.issuingUnitName = sysMagazine.magazineName;
                        }
                        if (sysMagazine.magazineType==2) {
                            e.issuingUnitName = sysMagazine.children?.map(e=>e.name).join(";");
                        }
                    }
                    e.checked = false;
                    e.showMore = false;
                    e.isMore = false;
                    return e;
                }) || [];
            })
        },
        addCart(item){
            EditCart({
                "userId": this.user.id,
                "resourceType":item.type,
                "resourceId":item.id,
                "price":item.price,
            }).then(res=>{
                if(res.code == -1){
                    this.$message.error(res.msg);
                    return;
                }
                this.$message.success(res.msg);
                this.$router.push("/cart");
            })
        },
        addOrder(item){
            let params = {
                orderUserId: this.user.id,
                orderResourceList:[{
                    resourceId: item.id,
                    resourceType: item.type,
                    resourceName: item.name,
                    unitPrice: item.price,
                    realPaid: item.price
                }]
            }
            EditOrder(params).then(res => {
                if (res.code == -1) {
                    this.$message.error(res.msg);
                    return;
                }
                this.$message.success(res.msg);
                // window.open(this.$router.resolve("/order/"+res.data.id).href)
            })
        },
        operateCollect(item){
            if (item.userCollectionStatus == 1) {
                CancelCollection({resourceId: item.id, resourceType: this.videoAudioTextActionMap[item.type]}).then(res => {
                    if (res.code == -1) {
                        this.$message.error(res.msg);
                        return;
                    }
                    this.$set(item,'userCollectionStatus',2)        
                    this.$set(item,'countCollection',item.countCollection -= 1)
                    this.$message.success(res.msg);
                })
            } else {
                AddCollection({resourceId: item.id, resourceType: this.videoAudioTextActionMap[item.type]}).then(res => {
                    if (res.code == -1) {
                        this.$message.error(res.msg);
                        return;
                    }
                    this.$set(item,'userCollectionStatus',1)
                    this.$set(item,'countCollection',item.countCollection += 1)
                    this.$message.success(res.msg);
                })
            }
        },
        opreateRecommend(item){
            if (item.userRecommendationStatus == 1) {
                CancelRecommendation({resourceId: item.id, resourceType: this.videoAudioTextActionMap[item.type]}).then(res => {
                    if (res.code == -1) {
                        this.$message.error(res.msg);
                        return;
                    }
                    this.$set(item,'userRecommendationStatus',2)
                    this.$set(item,'countRecommendation',item.countRecommendation -= 1)
                })
            } else {
                AddRecommendation({resourceId: item.id, resourceType: this.videoAudioTextActionMap[item.type]}).then(res => {
                    if (res.code == -1) {
                        this.$message.error(res.msg);
                        return;
                    }
                    this.$set(item,'userRecommendationStatus',1)
                    this.$set(item,'countRecommendation',item.countRecommendation += 1)
                    this.$message.success(res.msg);
                })
            }
        }
    },
}
</script>
<style scoped lang="scss">
.Main{
    height:100%;
    width: 100%;
    overflow: auto;
    .page_content{
        min-height: calc(100vh - 288px);
        position: relative;
        width: 1200px;
        margin: 20px auto;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 20px;
        .page_content_top{
            display: flex;
            gap: 20px;
            width: 100%;
            // align-items: flex-start;
        }
        .base-button--primary {
            background-color: #3F7FA7;
            border-color: #3F7FA7;
        }
        .base-button--text{
            border: 1px solid #3B7AA3;
            color: #3B7AA3;
            background-color: #fff;
        }
        .card{
            // padding: 18px 0px;
        }
        .base-divider--horizontal{
            margin: 16px 0;
        }
        .top_20{
            margin-top: 16px;
        }
        .page_content__left{
            display: flex;
            flex-direction: column;
            gap: 6px;
            width: 730px;
            .page_content__left__video_audio{
                .video-container {
                    width: 100%;
                    height: 400px;
                    margin: 16px 0;
                    border-radius: 8px;
                    overflow: hidden;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

                    video {
                        background-color: #000;
                    }
                }
            }
           .page_content__left_intro{
               .title{
                   font-size: 18px;
                   font-weight: 600;
                   color: #3B7AA3;
               }
           }
        }
        .page_content__right{
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 18px;
            .page_content__right—top{
                display: flex;
                flex-direction: column;
                padding: 6px 0px;
                .page_content__right__title{
                    font-size: 20px;
                    font-weight: 600;
                    color: #3B7AA3;
                }
               .page_content__right__info{
                    color: #666;
                }
                .page_content__right_tag{
                    display: flex;
                    align-items: center;
                    gap: 18px;
                    margin-top: 16px;
                    flex-wrap: wrap;
                }
                .base-tag{
                    border-radius: 16px;
                    padding: 0px 22px;
                }
            }
            .page_content__right—bottom{
                display: flex;
                flex-direction: column;
                padding: 6px 0px;
                .page_content__right—bottom_price_order{
                    .page_content__right—bottom_price{
                        font-size: 24px;
                        font-weight: 600;
                        color: #F97544;
                        text-align: center;
                    }
                    gap: 16px;
                    display: flex;
                    flex-direction: column;
                    .base-button+.base-button{
                        margin-left: 0px !important;
                    }
                }
               .page_content__right__operate{
                    margin-top: 16px;
                    display: flex;
                    justify-content: space-between;

                    .simple-action.is-active .Icon--like {
                        fill: #f64041;
                    }

                    .simple-action.is-active .Icon--Collect {
                        fill: #ddbb34;
                    }


                    .simple-action:hover .Icon--like {
                        fill: #f64041;
                    }

                    .simple-action:hover .Icon--Collect {
                        fill: #ddbb34;
                    }
                    
                    .simple-action{
                        padding: 6px 16px;
                        border-radius: 8px;
                        display: flex;
                        align-items: center;
                        border: 1px solid #3B7AA3;
                        cursor: pointer;
                        color: #4b5b76;

                        .Icon{
                            transition: fill .3s;
                            fill: #4b5b76;
                            padding-right: 2px;
                        }
                    }
                }
            }
        }
        .page_content__bottom{
            width: 100%;
            display: flex;
            padding: 8px 0;
            flex-direction: column;
           .page_content__bottom__title{
                font-size: 18px;
                font-weight: 600;
                color: #3B7AA3;
            }
            .page_content__bottom__content{
                display: flex;
                flex-direction: column;
               .page_content__bottom__content__item{
                    display: flex;
                    flex-direction: column;
                    gap: 20px;
                }
            }
        }
    }

}
</style>